package com.gzx.risk.core.apis.result.huarong;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.gzx.risk.core.apis.result.RiskResult;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.jetbrains.annotations.Nullable;

import java.util.Map;

/**
 * Huarong R9003 接口结果类
 * 用于存储和处理华融资信R9003接口的返回结果
 */
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class HuarongR9003 extends RiskResult {
    private String code;
    private String message;
    private Map<String, Object> data;
    private String signature;
    /**
     * 检查接口调用是否成功
     * @return 是否成功
     */
    public boolean isSuccess() {
        return "0000".equals(code);
    }

    /**
     * 根据层级路径字符串，从 data 中获取对应的值。
     * 路径格式示例: "rules_F001_F001A_A21"
     *
     * @param path 层级路径，使用下划线 "_" 分隔
     * @return 找到的值（已转为字符串），如果路径不存在、格式错误或值为null 返回""
     */
    public String getValueByPath(String path) {
        Object currentNode = this.getValue(path);
        if (currentNode == null) {
            return "";
        }
        return currentNode.toString();
    }

    public Double getScoreByPath(String path) {
        Object currentNode = this.getValue(path);
        if (currentNode == null) {
            return 0.0;
        }
        return Double.parseDouble(currentNode.toString());
    }

    private Object getValue(String path) {
        String[] pathSegments = path.split("_");
        if (pathSegments.length == 0) {
            return null;
        }

        Object currentNode = this.data;
        for (String segment : pathSegments) {
            if (!(currentNode instanceof Map)) {
                return null;
            }
            @SuppressWarnings("unchecked")
            Map<String, Object> currentMap = (Map<String, Object>) currentNode;
            currentNode = currentMap.get(segment);
            if (currentNode == null) {
                return null;
            }
        }
        return currentNode;
    }
}
